<?php
class db {
	var	$resource,
			$driver,
			$host,
			$user,
			$database,
			$res = false,
			$sql = "",
			$sql_history = array();


	function __construct($host="localhost",$user="root",$pass="",$database="",$driver="SQL Server"){
		$return = false;
		$this->driver = $driver;
		$this->database = $database;
		$this->host = $host;
		$this->user = $user;
		$connection_string = "DRIVER=$driver; SERVER=$host; uid=$user; pwd=$pass; DATABASE=$database";
		$this->resource = new COM("ADODB.Connection") or die("Cannot start ADO");
		$this->resource->Open($connection_string);


		if ($this->resource){
//			mysql_query('SET NAMES UTF8');
			$return = true;
		}
		return $return;
	}

	function query($sql,$to_log = true){
/*		if(is_object($this->res)){
			$this->res->Close();
		}
*/
		$this->res = false;
		$this->error = false;
		if ($to_log){
			$this->sql_history[] = $this->sql = $sql;
		}
		dump($this->resource,$sql);

		$this->res = $this->resource->Execute($sql);

/*		$res = new COM("ADODB.Recordset");
		$this->res = $res->Open($sql,$this->resource);
*/
		if (!$this->res){
			$this->error = array('sql' => $sql/*, 'error' => $this->resource->ErrorMsg()*/);
			$this->error_log[] = $this->error;
		}
		return $this->res;
	}

	function insert_id(){
		return $this->resource->insert_id;
	}

	function result_count(){
		return $rec->Fields->Count;
	}

	function affected_rows(){
		return $this->resource->affected_rows;
	}

	function deleted_rows(){
		return $this->resource->affected_rows;
	}

	function updated_rows(){
		return $this->resource->affected_rows;
	}

	function inserted_rows(){
		return $this->resource->affected_rows;
	}

	function table_info(){
		$sql = "SHOW TABLE STATUS LIKE '$tablename'";
		$info = $this->query_line($sql);
		return $info;
	}

	function next_id($tablename){
		$table_info = $this->table_info();
		return $table_info['Auto_increment'];
	}

	function fetch($res=null){
		if ($res==null){
			$res = &$this->res;
		}
		$return = false;
		if (!$res->EOF){
			$return = array();
			$num_columns = $res->Fields->Count();
			for ($i=0; $i < $num_columns; $i++) {
				$return[$res->Fields($i)->name] = $res->Fields($i)->value;
			}
			$res->MoveNext();
  		}
		return $return;
	}

	function query_line($sql){
		$return = false;
		if ($this->query($sql)){
			$return = array();
			if($row = $this->fetch()){
				$return = $row;
			}
		}
		return $return;
	}

	function query_value($sql){
		$return = $this->query_line($sql);
		if (!empty($return) && is_array($return)){
			$return = array_shift($return);
		}
		return $return;
	}

	function query_assoc($sql,$key=false){
		$return = false;
		if ($this->query($sql)){
			$return = array();
			while($row = $this->fetch()){
				if ($key===false || !array_key_exists($key,$row)){
					$return[] = $row;
				}else{
					$return[$row[$key]] = $row;
				}
			}
		}
		return $return;
	}

/*
	A este método se pasa SQL en formato "SELECT SQL_CALC_FOUND_ROWS ..."
	al segundo parámetro se devuelve la cantidad de resultados (para paginación)
*/
	function query_assoc_count($sql,&$count=0,$key=false){
		$return = false;
		if ($this->query($sql)){

			$return = array();
			while($row = $this->fetch()){
				if ($key===false || !array_key_exists($key,$row)){
					$return[] = $row;
				}else{
					$return[$row[$key]] = $row;
				}
			}
			$count = $this->query_value("SELECT FOUND_ROWS()");		//devuelve cantidad ignorando LIMIT

		}
		return $return;
	}

//========================================================================================================

	function add_history($action,$table,$record_id,$values=null){
/*		global $user;
		$login = block($user->login);
		$action = block($action);
		$table = block($table);
		$record_id = (int)$record_id;
		$values = !is_null($values)?block(serialize($values)):'';
		$sql = "INSERT INTO $this->tblHistory (`user`,`action`,`table`,`record_id`,`date`,`dump`) VALUES ('$login','$action','$table','$record_id',NOW(),'$values')";
		$this->query($sql,$to_log = false);
*/
	}

	function insert($table,$values){
		$return = false;
		if (!empty($values)){
			$table = block($table);
			$field_list = array();
			$value_list = array();
			foreach($values as $key=>$value){
				$field_list[] = "`".block($key)."`";
				$value_list[] = is_array($value) ? array_shift($value) : "'".block($value)."'";
			}
			$sql = "INSERT INTO `$table` (".implode(',',$field_list).") VALUES (".implode(',',$value_list).")";
			if ($this->query($sql) && !$this->error){
				$this->add_history('insert',$table,$this->insert_id(),$values);
				$return = true;
			}
		}else{
			$this->error = array('event' => 'No hay nada que insertar');
			$this->error_log[] = $this->error;
		}
		return $return;
	}

	function update($table,$values,$id,$where=false,$check_id=true){
		$return = false;
		if (isset($values['id'])){
			unset($values['id']);
		}
		if (!empty($values)){
			$table = block($table);
			$set = array();
			foreach($values as $key=>$value){
				//si el valor se pasa como array - no añadimos comillas para poder usar funciones como NOW()
				if (is_array($value)){
					$set[] = "`".block($key)."` =  ".array_shift($value)."";
				}else{
					$set[] = "`".block($key)."` = '".block($value)."'";
				}
			}
			$id = (int)$id;
			if ($id && !$where){
				$where = "`id` = '$id'";
			}elseif($where){
//				$where = $where;
			}
			if ($check_id){
				$sql = "SELECT id FROM `$table` WHERE $where LIMIT 1";
				$id = (int)$this->query_value($sql);
			}
			if (!$check_id || $id){
				$sql = "UPDATE `$table` SET ".implode(',',$set)." WHERE $where LIMIT 1";
				if ($this->query($sql) && !$this->error){
					$this->add_history('update',$table,$id,$values);
					$return = true;
				}
			}else{

			}
		}else{
			$this->error = array('event' => 'No hay nada que actualizar');
			$this->error_log[] = $this->error;
		}
		return $return;
	}

	function delete($table,$id,$where=false){
		$return = false;
		$id = (int)$id;
		if ($id && !$where){
			$where = "`id` = '$id'";
		}elseif($where){
			$where = $where;
		}
		$sql = "SELECT * FROM `$table` WHERE $where LIMIT 1";
		$values = $this->query_line($sql);
		$id = isset($values['id'])?(int)$values['id']:0;
		$sql = "DELETE FROM `$table` WHERE $where LIMIT 1";
		if ($this->query($sql) && !$this->error){
			$this->add_history('delete',$table,$id,$values);
			$return = true;
		}
		return $return;
	}
}
?>
